/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.config.datasource;

import com.huawei.housekeeper.commonutils.constants.NumberConstant;

import lombok.extern.log4j.Log4j2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

/**
 * 读取租户数据源
 *
 * @author lWX1128557
 * @since 2022-03-07
 */
@Component
@Log4j2
public class DataSourceProperties {
    @Autowired
    private DataSource dataSource;

    /**
     * 获取所有租户schema
     *
     * @return 租户schema
     */
    public List<String> getSchemas() {
        // 查询所有数据库
        List<String> tenantSchemas = new ArrayList<>();
        String sql = "select SCHEMA_NAME from INFORMATION_SCHEMA.SCHEMATA";

        try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql)) {
            while (resultSet.next()) {
                String schema = resultSet.getString(NumberConstant.ONE);

                // 获取以tenant开头的数据源
                if (schema.startsWith("tenant")) {
                    tenantSchemas.add(schema);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return tenantSchemas;
    }
}